import CardPanel from '@/components/CardPanel';
import CommonDrawer from '@/components/CommonDrawer';
import ImageViewer from '@/components/ImageViewer';
import { BOOLEAN_MAP } from '@/constants/enums';
import useMaterial from '@/hooks/useMaterial';
import request from '@/utils/request';
import { useRequest } from 'ahooks';
import { Button, Descriptions } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo } from 'react';
import styles from './index.less';

const Detail = (props) => {
  const {
    source = 'default',
    open,
    record: recordProps,
    onCancel,
    preBtnProps,
    nextBtnProps,
    numberStep,
  } = props;
  const { materialTypeMap } = useMaterial();

  // 懒得改代码，把原来从表格传过来的record换成详情查询的结果，方便其他模块复用
  const { data: record, runAsync } = useRequest(
    async (params) => {
      const res = await request({
        url: '/datas/weight/detail',
        method: 'GET',
        params,
      });
      return res;
    },
    { manual: true },
  );

  useEffect(() => {
    if (open && recordProps) {
      runAsync({ weightId: recordProps?.weightId });
    }
  }, [open, recordProps]);

  // 计算总支出=装车费+卸车费+路桥费用+ETC费用+司机薪金+轮胎损耗+信息费+篷布费+过磅费+上车台费+下车台费+充电费+交警罚款+维修费+其他费用
  const totalPrice = useMemo(() => {
    const loadPrice = record?.loadPrice || 0;
    const unloadPrice = record?.unloadPrice || 0;
    const roadPrice = record?.roadPrice || 0;
    const etcPrice = record?.etcPrice || 0;
    const driverPrice = record?.driverPrice || 0;
    const tyrePrice = record?.tyrePrice || 0;
    const infoPrice = record?.infoPrice || 0;
    const tarpaulinPrice = record?.tarpaulinPrice || 0;
    const passWeightPrice = record?.passWeightPrice || 0;
    const upCarPrice = record?.upCarPrice || 0;
    const downCarPrice = record?.downCarPrice || 0;
    const chargePrice = record?.chargePrice || 0;
    const trafficTicket = record?.trafficTicket || 0;
    const repairPrice = record?.repairPrice || 0;
    const otherPrice = record?.otherPrice || 0;
    return (
      loadPrice +
      unloadPrice +
      roadPrice +
      etcPrice +
      driverPrice +
      tyrePrice +
      infoPrice +
      tarpaulinPrice +
      passWeightPrice +
      upCarPrice +
      downCarPrice +
      chargePrice +
      trafficTicket +
      repairPrice +
      otherPrice
    );
  }, [record]);

  // 计算任务营收=线路运价*卸车净重
  const taskPrice = useMemo(() => {
    const linePrice = record?.linePrice || 0;
    const unloadWeight = record?.unloadWeight || 0;
    return linePrice * unloadWeight;
  }, [record]);

  // 计算磅差相关数据
  const discrepancyWeight = useMemo(() => {
    const loadWeight = record?.loadWeight || 0;
    const unloadWeight = record?.unloadWeight || 0;
    if (loadWeight > 0 && unloadWeight > 0) {
      return loadWeight - unloadWeight;
    }
    return 0;
  }, [record]);

  const standardLossWeight = useMemo(() => {
    const loadWeight = record?.loadWeight || 0;
    const lossRatio = record?.lossRatio || 0;
    return loadWeight * lossRatio;
  }, [record]);

  const lossWeight = useMemo(() => {
    return discrepancyWeight > standardLossWeight
      ? discrepancyWeight - standardLossWeight
      : 0;
  }, [discrepancyWeight, standardLossWeight]);

  const lossPrice = useMemo(() => {
    const discrepancyPrice = record?.discrepancyPrice || 0;
    return lossWeight * discrepancyPrice;
  }, [lossWeight, record]);

  // 计算结算重量
  const weights = useMemo(() => {
    const loadWeight = record?.loadWeight || 0;
    const unloadWeight = record?.unloadWeight || 0;
    if (loadWeight > 0 && unloadWeight > 0) {
      return Math.min(loadWeight, unloadWeight);
    } else if (loadWeight > 0) {
      return loadWeight;
    } else if (unloadWeight > 0) {
      return unloadWeight;
    }
    return 0;
  }, [record]);

  // 计算结算金额=任务营收-损耗金额
  const settlement = useMemo(() => {
    return taskPrice - lossPrice;
  }, [taskPrice, lossPrice]);

  // 计算营收毛利=结算金额-总支出
  const grossProfit = useMemo(() => {
    return settlement - totalPrice;
  }, [settlement, totalPrice]);

  // 计算毛利率=营收毛利/结算金额*100%
  const profitMargin = useMemo(() => {
    return grossProfit && settlement ? (grossProfit / settlement) * 100 : 0;
  }, [grossProfit, settlement]);

  const images = useMemo(() => {
    const imgs = [];
    if (source === 'default') {
      record?.driverImage && imgs.push(record?.driverImage);
      record?.loadWeightCodeImage && imgs.push(record?.loadWeightCodeImage);
      record?.unloadWeightCodeImage && imgs.push(record?.unloadWeightCodeImage);
    } else {
      record?.driverImage && imgs.push(record?.driverImage);
    }

    return imgs?.filter(Boolean);
  }, [source, record]);

  return (
    <CommonDrawer
      title={
        record ? `磅单详情${numberStep ? `(${numberStep})` : ''}` : '磅单详情'
      }
      open={open}
      onClose={onCancel}
      width="100%"
      destroyOnHidden
      footer={
        <>
          <Button onClick={onCancel}>关闭</Button>
          {record && <Button {...preBtnProps}>上一条</Button>}
          {record && <Button {...nextBtnProps}>下一条</Button>}
        </>
      }
    >
      <div className={styles.container}>
        <div className={styles.left}>
          <div className={styles.title}>
            <span>司机上传磅单</span>
          </div>
          <div className={styles.imgContainer}>
            <ImageViewer urls={images} />
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.title}>
            <span>基本信息</span>
            {record ? (
              <span style={{ marginLeft: 10, fontWeight: 'normal' }}>
                ({record.time})
              </span>
            ) : (
              ''
            )}
          </div>
          <Descriptions column={2} size="small" bordered>
            <Descriptions.Item label="线路">
              {record?.lineName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="车牌号">
              {record?.license || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="装车司机">
              {record?.loadDriver || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="卸车司机">
              {record?.unloadDriver || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="物料类型">
              {materialTypeMap[record?.type] || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="客户名称">
              {record?.customerName || '-'}
            </Descriptions.Item>
            {source === 'default' && (
              <>
                <Descriptions.Item label="已交票">
                  {BOOLEAN_MAP[record?.returnCompany] || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="交票日期">
                  {record?.returnDate || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="已结算">
                  {BOOLEAN_MAP[record?.balancePrice] || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="结算日期">
                  {record?.balanceDate || '-'}
                </Descriptions.Item>
              </>
            )}
            <Descriptions.Item label="备注" span={2}>
              {record?.remark || '-'}
            </Descriptions.Item>
          </Descriptions>
          <CardPanel title="磅单信息" style={{ marginTop: 8 }}>
            <section className={styles.weightInfoContent}>
              <div className={styles.weightInfoContentItem}>
                <Descriptions title="装车信息" column={2} size="small" bordered>
                  <Descriptions.Item label="装车磅单号">
                    {record?.loadWeightCode || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="装车时间">
                    {record?.loadTime
                      ? dayjs(record.loadTime).format('YYYY-MM-DD HH:mm:ss')
                      : '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="装车毛重">
                    {record?.loadEmptyWeight || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="装车皮重">
                    {record?.loadTotalWeight || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="装车净重">
                    {record?.loadWeight || '-'}
                  </Descriptions.Item>
                </Descriptions>
              </div>
              <div className={styles.weightInfoContentItem}>
                <Descriptions title="卸车信息" column={2} size="small" bordered>
                  <Descriptions.Item label="卸车磅单号">
                    {record?.unloadWeightCode || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="卸车时间">
                    {record?.unloadTime
                      ? dayjs(record.unloadTime).format('YYYY-MM-DD HH:mm:ss')
                      : '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="卸车毛重">
                    {record?.unloadEmptyWeight || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="卸车皮重">
                    {record?.unloadTotalWeight || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="卸车净重">
                    {record?.unloadWeight || '-'}
                  </Descriptions.Item>
                </Descriptions>
              </div>
            </section>
          </CardPanel>
          <CardPanel title="费用信息" style={{ marginTop: 8 }}>
            <div style={{ padding: '0 16px' }}>
              <Descriptions column={3} size="small" bordered>
                <Descriptions.Item label="装车费用（元）">
                  {record?.loadPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="卸车费用（元）">
                  {record?.unloadPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="路桥费用（元）">
                  {record?.roadPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="ETC费用（元）">
                  {record?.etcPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="司机薪金（元）">
                  {record?.driverPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="轮胎损耗（元）">
                  {record?.tyrePrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="信息费（元）">
                  {record?.infoPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="篷布费（元）">
                  {record?.tarpaulinPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="过磅费（元）">
                  {record?.passWeightPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="上车台费（元）">
                  {record?.upCarPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="下车台费（元）">
                  {record?.downCarPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="充电费（元）">
                  {record?.chargePrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="交警罚款（元）">
                  {record?.trafficTicket || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="维修费（元）">
                  {record?.repairPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="其他费用（元）">
                  {record?.otherPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="总支出（元）">
                  {totalPrice}
                </Descriptions.Item>
              </Descriptions>
            </div>
          </CardPanel>
          <CardPanel title="磅差信息" style={{ marginTop: 8 }}>
            <div style={{ padding: '0 16px' }}>
              <Descriptions column={3} size="small" bordered>
                <Descriptions.Item label="结算重量（吨或方）">
                  {weights || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="磅差（吨或方）">
                  {discrepancyWeight || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="磅差单价（元/吨或方）">
                  {record?.discrepancyPrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="磅差系数">
                  {record?.lossRatio || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="合理损耗（吨或方）">
                  {standardLossWeight || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="扣损重量（吨或方）">
                  {lossWeight || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="损耗金额（元）">
                  {lossPrice || '-'}
                </Descriptions.Item>
              </Descriptions>
            </div>
          </CardPanel>
          <CardPanel title="任务营收" style={{ marginTop: 8 }}>
            <div style={{ padding: '0 16px' }}>
              <Descriptions column={3} size="small" bordered>
                <Descriptions.Item label="线路运价（元/吨）">
                  {record?.linePrice || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="任务营收（元）">
                  {taskPrice}
                </Descriptions.Item>
                <Descriptions.Item label="结算金额（元）">
                  {settlement}
                </Descriptions.Item>
                <Descriptions.Item label="营收毛利（元）">
                  {grossProfit}
                </Descriptions.Item>
                <Descriptions.Item label="毛利率（%）">
                  {profitMargin.toFixed(2)}%
                </Descriptions.Item>
              </Descriptions>
            </div>
          </CardPanel>
        </div>
      </div>
    </CommonDrawer>
  );
};

export default Detail;
